package com.xiaozhen.system.controller;

import com.xiaozhen.security.controller.BaseController;
import com.xiaozhen.common.core.domain.AjaxResult;
import com.xiaozhen.common.core.domain.system.SysDept;
import com.xiaozhen.system.service.SysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/8/19 14:20
 * @description:
 */
@RestController
@Api(tags = "系统部门接口")
@RequestMapping("/sysDept")
public class SysDeptController extends BaseController {

    @Autowired
    private SysDeptService sysDeptService;

    @ApiOperation("获取部门下拉树列表")
    @GetMapping("/treeSelect")
    public AjaxResult treeSelect(SysDept dept) {
        List<SysDept> depts = sysDeptService.selectDeptList(dept);
        return AjaxResult.success(sysDeptService.buildDeptTreeSelect(depts));
    }

    @ApiOperation("获取部门列表")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept) {
        List<SysDept> deptList = sysDeptService.selectDeptList(dept);
        return AjaxResult.success(sysDeptService.buildDeptTree(deptList));
    }

    @ApiOperation("新增部门")
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        if (!sysDeptService.checkDeptNameUnique(dept)) {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getCurrentUserId());
        dept.setCreateTime(LocalDateTime.now());
        return toAjax(sysDeptService.insertSysDept(dept));
    }

    @ApiOperation("修改部门")
    @PutMapping("/update")
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        if (!sysDeptService.checkDeptNameUnique(dept)) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        if (dept.getParentId().equals(dept.getDeptId())) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        dept.setUpdateBy(getCurrentUserId());
        dept.setUpdateTime(LocalDateTime.now());
        return toAjax(sysDeptService.updateSysDept(dept));
    }

    @ApiOperation("删除部门")
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (sysDeptService.hasChildByDeptId(deptId)) {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (sysDeptService.checkDeptExistUser(deptId)) {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(sysDeptService.deleteDeptById(deptId));
    }
}
